(ns acst.models.roles
  (:use acst.config.error-config)
  (:require [acst.models.db :as db]))


;;数据库初始化模型
(def permission {
                 :follow 2r00000001
                 :comment 2r00000010
                 :write-memos 2r00000100
                 :write-articles 2r00001000
                 :moderate-comments 2r00010000
                 :administer 2r10000000
                 })

(def user-role {:permission
                (-> (permission :write-memos)
                    (bit-or (permission :follow))
                    (bit-or (permission :comment))
                 )
                :name "user"})


(def moderator {:permission
                (-> (permission :moderate-comments)
                    (bit-or (permission :follow))
                    (bit-or (permission :follow))
                    (bit-or (permission :comment))
                    (bit-or (permission :write-memos))
                    (bit-or (permission :write-articles)))
                :name "moderator"})


(def administrator {:permission (permission :administer)
                    :name "administrator"})

(def roles [user-role moderator administrator])


(defn get-permission [user_id]
  (get (first (db/query (:role-not-found roles-error)
            [
             "SELECT permission
             FROM users
             WHERE user_id = ?" user_id])) :permission))


;;数据库操作模型
(defn is-admin? [user_id]
  (= (administrator :permission) (get-permission user_id)))

(defn is-user? [user_id]
  (= (user-role :permission) (get-permission user_id)))

(defn is-moderator? [user_id]
  (= (moderator :permission) (get-permission user_id)))

(defmacro if-is-admin [user_id then & else]
  `(if (is-admin? ~user_id) ~then ~@else))

